//
//  UIView+frameInMainScreen.m
//  计算一个控件在屏幕的位置
//
//  Created by Mac on 16/1/5.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "UIView+frameInMainScreen.h"

@implementation UIView (frameInMainScreen)

- (CGRect)getFrameInMainScreen {
    //遍历这个控件的所有层次控件，包括自身
    NSMutableArray *views = [[NSMutableArray alloc] init];
    id sunView = self;
    while (YES) {
        id view = [sunView superview];
        if (view != nil) {
            [views addObject:view];
            sunView = view;
        } else {
            [views addObject:self];
            break;
        }
    }
    CGFloat sumx = 0;
    CGFloat sumy = 0;
    for (NSInteger i = views.count; i > 0; i--) {
        UIView *view = views[i-1];
        sumy += view.frame.origin.y;
        sumx += view.frame.origin.x;
        if ([view class] == [UIScrollView class]) {
            UIScrollView *scrollView = (UIScrollView *)view;
            sumy -= scrollView.contentOffset.y;
            sumx -= scrollView.contentOffset.x;
        }
    }
    return CGRectMake(sumx, sumy, self.frame.size.width, self.frame.size.height);
}

- (CGFloat)willBeCoverWithkeyboardHeight:(CGFloat)height {
    CGFloat Y = [self getFrameInMainScreen].origin.y;
    CGFloat spacing = Y - ([UIScreen mainScreen].bounds.size.height - height) + self.frame.size.height;
    if (spacing<0) {
        return 0;
    } else {
        return spacing;
    }
}



@end
